import { IModel } from '../../models'
import { encodePassword, validatePassword } from '../../utils/password'
import { ErrorReason } from '../../utils'
import { Context } from '../../types'
import { CommonSecret } from '../../config/secret'
import jwt from 'jsonwebtoken'
import BaseService from '../base'

export default class UserService extends BaseService {
  public static async register(model: IModel, params) {
    /**
     * 1. 生成随机 salt 值
     * 2. 使用 salt 值与 fp 获取对应的 md5
     */
    const { fp, ...rest } = params

    const [salt, secret] = encodePassword(fp)
    await model.create({
      ...rest,
      salt,
      secret,
    })
    return {}
  }

  public static async login(ctx: Context, params) {
    const { fp, username } = params

    const info = await ctx.model.findOne({
      where: {
        username,
      },
    })

    if (info === null) return Promise.reject(ErrorReason.UserNotExistError)

    const { id, salt, secret } = info.dataValues
    const validation = validatePassword(fp, salt, secret)
    if (validation) {
      // token 中置放 相关信息, 方便在 middleware 中获取信息
      const token = jwt.sign(
        {
          id,
        },
        CommonSecret,
        {
          expiresIn: '1d',
        },
      )
      // header 中置放 token
      ctx.set('token', token)
    }
    return validation ? {} : Promise.reject(ErrorReason.UserValidatedError)
  }
}
